package se.rende.schema2ical.client;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.datepicker.client.DatePicker;

public class Schema2ical implements EntryPoint {
	private static final DateTimeFormat schemaDateFormat = DateTimeFormat.getFormat("yyyy-MM-dd");
	Schema schema = new Schema();
	private FlexTable passTimeTable;
	private TextArea passes;
	private Label passesSummary;
	private StorageService storageService = new StorageService();
	private Label statusMessage;
	private DatePicker datePicker;
	private Label startDate;

	public void onModuleLoad() {
		storageService.loadSchema(new StorageResponse<Schema>() {

			@Override
			public void success(Schema schema) {
				Schema2ical.this.schema = schema;
				copySchemaToFields();
			}

			@Override
			public void failure(String message) {
				statusMessage.setText(message);
			}
		});

		RootPanel rootPanel = RootPanel.get("schemaEntry");

		VerticalPanel verticalPanel = new VerticalPanel();
		rootPanel.add(verticalPanel);

		HorizontalPanel horizontalPanel = new HorizontalPanel();
		verticalPanel.add(horizontalPanel);

		datePicker = new DatePicker();
		startDate = new Label();
		startDate.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				datePicker.setVisible(!datePicker.isVisible());
			}
		});
		datePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {
			@Override
			public void onValueChange(ValueChangeEvent<Date> event) {
				Date date = event.getValue();
				String dateString = schemaDateFormat
						.format(date);
				startDate.setText(dateString);
				datePicker.setVisible(false);
			}
		});

		datePicker.setValue(new Date(), true);
		datePicker.setVisible(false);

		horizontalPanel.add(new Label("Start-datum:"));
		horizontalPanel.add(startDate);
		horizontalPanel.add(datePicker);

		// Label lblVeckorPerCykel = new Label("Start date:");
		// horizontalPanel.add(lblVeckorPerCykel);
		//
		// startDate = new TextBox();
		// horizontalPanel.add(startDate);
		// startDate.setWidth("45px");

		Label lblPassOchTider = new Label("Pass-tider:");
		rootPanel.add(lblPassOchTider);

		passTimeTable = new FlexTable();
		rootPanel.add(passTimeTable);

		Button btnAddPassTime = new Button("Add");
		btnAddPassTime.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				addPassTimeRow();
			}

		});
		rootPanel.add(btnAddPassTime);

		Label lblPass = new Label("Pass:");
		rootPanel.add(lblPass);
		passes = new TextArea();
		passes.addChangeHandler(new ChangeHandler() {

			@Override
			public void onChange(ChangeEvent event) {
				updatePassesSummary();
			}

		});
		passes.addKeyUpHandler(new KeyUpHandler() {

			@Override
			public void onKeyUp(KeyUpEvent event) {
				updatePassesSummary();
			}
		});
		rootPanel.add(passes);

		passesSummary = new Label();
		passesSummary.setText("no passes");
		rootPanel.add(passesSummary);

		HorizontalPanel horizontalPanel_1 = new HorizontalPanel();
		horizontalPanel_1
				.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
		rootPanel.add(horizontalPanel_1);

		Button btnSave = new Button("Save");
		btnSave.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				copyFieldsToSchema();
				storageService.saveSchema(schema,
						new StorageResponse<String>() {

							@Override
							public void success(String s) {
								statusMessage.setText("schema is saved");
							}

							@Override
							public void failure(String message) {
								statusMessage.setText(message);
							}
						});
			}

		});
		horizontalPanel_1.add(btnSave);

		Button getICalFileButton = new Button("New button");
		getICalFileButton.setText("Get iCal file");
		horizontalPanel_1.add(getICalFileButton);
		getICalFileButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				Window.open("/schema2ical/getICal", "icaldownload", "");
			}
		});
		passes.setSize("175px", "90px");

		statusMessage = new Label();
		rootPanel.add(statusMessage);

	}

	private void copyFieldsToSchema() {
		schema.setStartDate(schemaDateFormat.format(datePicker.getValue()));
		int rowCount = passTimeTable.getRowCount();
		for (int i = 0; i < rowCount; i++) {
			System.out.println("i=" + i);
			PassTime passTime = schema.getPassTimes().get(i);
			TextBox textBox = (TextBox) passTimeTable.getWidget(i, 0);
			passTime.setName(textBox.getText().charAt(0));
			textBox = (TextBox) passTimeTable.getWidget(i, 1);
			passTime.setFromTime(textBox.getText());
			textBox = (TextBox) passTimeTable.getWidget(i, 3);
			passTime.setToTime(textBox.getText());
		}
		schema.setPasses(passes.getText());
	}

	private void copySchemaToFields() {
		datePicker.setValue(schemaDateFormat.parse(schema.getStartDate()), true);
		List<PassTime> passTimes = schema.getPassTimes();
		for (int i = 0; i < passTimes.size(); i++) {
			PassTime passTime = passTimes.get(i);
			if (i >= passTimeTable.getRowCount()) {
				addPassTimeTableRow(i, passTime);
			} else {
				setPassTimeTableRow(i, passTime);
			}
		}
		passes.setText(schema.getPasses());
		updatePassesSummary();
	}

	private void updatePassesSummary() {
		schema.setPasses(passes.getText());
		passesSummary.setText(schema.getPassCount() + " passes");
	}

	private void addPassTimeRow() {
		int rowCount = passTimeTable.getRowCount();
		PassTime passTime = new PassTime((char) ('a' + rowCount), "", "");
		schema.getPassTimes().add(passTime);

		addPassTimeTableRow(rowCount, passTime);
		TextBox fromTextBox = (TextBox) passTimeTable.getWidget(rowCount, 1);
		fromTextBox.setFocus(true);
	}

	private void addPassTimeTableRow(int row, PassTime passTime) {
		TextBox nameTextBox = new TextBox();
		nameTextBox.setText(Character.toString(passTime.getName()));
		nameTextBox.setWidth("30px");
		passTimeTable.setWidget(row, 0, nameTextBox);

		TextBox fromTextBox = new TextBox();
		fromTextBox.setText(passTime.getFromTime());
		fromTextBox.setWidth("50px");
		passTimeTable.setWidget(row, 1, fromTextBox);

		passTimeTable.setText(row, 2, " - ");

		TextBox toTextBox = new TextBox();
		toTextBox.setText(passTime.getToTime());
		toTextBox.setWidth("50px");
		passTimeTable.setWidget(row, 3, toTextBox);
	}

	private void setPassTimeTableRow(int row, PassTime passTime) {
		TextBox nameTextBox = (TextBox) passTimeTable.getWidget(row, 0);
		nameTextBox.setText(Character.toString(passTime.getName()));

		TextBox fromTextBox = (TextBox) passTimeTable.getWidget(row, 1);
		fromTextBox.setText(passTime.getFromTime());

		TextBox toTextBox = (TextBox) passTimeTable.getWidget(row, 3);
		toTextBox.setText(passTime.getToTime());
	}
}
